
import md5 from 'js-md5'
import CryptoJS from 'crypto-js'
let keyStr = 'f50217eeef726d2b'

// 加密
function encrypt (word) {
  keyStr = keyStr || 'f50217eeef726d2b'
  var key = CryptoJS.enc.Utf8.parse(keyStr)// Latin1 w8m31+Yy/Nw6thPsMpO5fg==
  var srcs = CryptoJS.enc.Utf8.parse(word)
  var encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return encrypted.toString()
}

// 解密
// export function decrypt(word, keyStr){
function decrypt (word) {
  keyStr = keyStr || 'f50217eeef726d2b'
  var key = CryptoJS.enc.Utf8.parse(keyStr)// Latin1 w8m31+Yy/Nw6thPsMpO5fg==
  var decrypt = CryptoJS.AES.decrypt(word, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return CryptoJS.enc.Utf8.stringify(decrypt).toString()
}

function toParamsStr (params) {
  let url = ''
  for (var key in params) {
    if (params.hasOwnProperty(key)) {
      var v = params[key]
      if (v !== '') {
        url += key + '=' + params[key] + '&'
      }
    }
  }
  return url.slice(0, -1)
}

function toMd5Str (obj) {
  let str = ''
  Object.entries(obj).map(([key, val]) => {
    str += '' + key + val
  })
  return md5(str)
}

export function toSgin (params) {
  return encrypt(toMd5Str(params) + '|' + toParamsStr(params))
}
